package com.lagou.controller;

import com.lagou.domain.Order;
import com.lagou.repository.OrderRepository;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class OrderController {

    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Autowired
    private OrderRepository orderRepository;

    // 发起付款请求
    @RequestMapping(value = "/create-order",produces = MediaType.APPLICATION_JSON_VALUE)
    public String createOrder() {

        Order order = new Order();
        order.setName("华为手机");
        order.setMoney(1000.0);
        order.setStatus(1);
        order.setCreateTime(ZonedDateTime.now());
        order = orderRepository.save(order);

        rabbitTemplate.convertAndSend("ex.pay","pay","购买华为手机，待支付1000元，id_" +order.getId());
        return "购买华为手机，待支付1000元,id是" + order.getId() + ",有效支付时间是10s";
    }

    // 对 id 订单进行付款
    @RequestMapping(value = "/pay-order/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public String payOrder(@PathVariable Integer id){
        System.out.println(id);
        Optional<Order> orderOptional = orderRepository.findById(id);
        Order order = new Order();
        if(orderOptional.isPresent()) {
            order = orderOptional.get();
            // 检查时间是否过期
            ZonedDateTime now = ZonedDateTime.now();
            if(order.getCreateTime().plusSeconds(10L).isBefore(now)) {
                return "该订单已过期..";
            }
            order = orderOptional.get();
            order.setStatus(2);
            orderRepository.save(order);
            rabbitTemplate.receiveAndConvert("q.pay");
        }

        return "支付成功";
    }


    // 拒绝付款
    @RequestMapping("/reject-order")
    public String rejectOrder(){
        String rejectPay = String.valueOf(rabbitTemplate.receiveAndConvert("q.pay.dlx"));
        return rejectPay;
    }


    // 获取 id 付款请求
    @RequestMapping(value = "/order/{id}")
    public Order getOrder(@PathVariable Integer id) {
        Order order = orderRepository.findById(id).get();
        order.setName(order.getName() + " " + (order.getStatus()==1?"待支付":order.getStatus()==2?"支付成功":"支付失败"));
        return order;
    }

    // 获取所有因为超时取消的列表
    @RequestMapping(value = "/order/cancel")
    public List<Order> getOrder() {
        List<Order> orders = orderRepository.findAllByStatus(3);
        for (Order order : orders) {
            order.setName(order.getName() + " " + (order.getStatus()==1?"待支付":order.getStatus()==2?"支付成功":"支付失败"));
        }
        return orders;
    }


}